//
//  YFDataBaseManager.m
//  project
//
//  Created by yefei on 2019/4/24.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFDatabaseManager.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "YFFileManager.h"

@interface YFDatabaseManager ()

@property (nonatomic, strong) FMDatabaseQueue *databaseQueue;

@end

@implementation YFDatabaseManager

// RongCloudIMDataBase数据库
static NSString *const RongCloudIMDatabase = @"RongCloudIMDatabase";

// IM用户表
static NSString *const userTableName = @"USERTABLE";


#pragma mark - 绝对单例
static YFDatabaseManager *_manager = nil;
+ (instancetype)shared {
    
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        _manager = [[[self class] alloc] init];
    });
    return _manager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        _manager = [super allocWithZone:zone];
    });
    return _manager;
}

- (instancetype)copyWithZone:(NSZone *)zone {
    return _manager;
}

- (instancetype)mutableCopyWithZone:(NSZone *)zone {
    return _manager;
}

#pragma mark - 将用户信息存入数据库
- (void(^)(NSString *userId, NSString *userName, NSString *portraitUri))insertUser {
    
    __weak typeof(self) weakSelf = self;
    return ^(NSString *userId, NSString *userName, NSString *portraitUri) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        NSString *insertUserSql = @"REPLACE INTO USERTABLE (userid, name, portraitUri) VALUES (?, ?, ?)";
        [strongSelf.databaseQueue inDatabase:^(FMDatabase * _Nonnull db) {
            [db executeUpdate:insertUserSql, userId, userName, portraitUri];
        }];
    };
}

#pragma mark - 将用户信息列表存入数据库
- (void(^)(NSArray<NSDictionary<NSString *, NSString *> *> *userList, void(^result)(BOOL isSuccess)))insertUserList {
    
    __weak typeof(self) weakSelf = self;
    return ^(NSArray<NSDictionary<NSString *, NSString *> *> *userList, void(^result)(BOOL isSuccess)) {
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            
            [strongSelf.databaseQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
                for (NSDictionary<NSString *, NSString *> *userInfo in userList) {
                    NSString *insertUserSql = @"REPLACE INTO USERTABLE (userid, name, portraitUri) VALUES (?, ?, ?)";
                    NSString *portraitUri = userInfo[@"portraitUri"];
                    NSString *userId = userInfo[@"userId"];
                    NSString *userName = userInfo[@"userName"];
                    [db executeUpdate:insertUserSql, userId, userName, portraitUri];
                }
            }];
            result(YES);
        });
    };
}

#pragma mark - 删除用户




#pragma mark - 创建消息好友消息信息表
- (void)createUserInfoTable {
    
    __weak typeof(self) weakSelf = self;
    [self.databaseQueue inDatabase:^(FMDatabase * _Nonnull db) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        // 创建user信息表
        if (!strongSelf.tableIsExist(userTableName, db)) {
            
            NSString *createTableSql = @"CREATE TABLE USERTABLE (id integer PRIMARY "
                                       @"KEY autoincrement, userid text, name text, "
                                        @"portraitUri text";
            [db executeUpdate:createTableSql];
            NSString *createIndexSql = @"CREATE unique INDEX idx_userid ON USERTABLE(userid);";
            [db executeUpdate:createIndexSql];
        }
    }];
}


#pragma mark - 查询表是否存在
- (BOOL(^)(NSString *tableName, FMDatabase *db))tableIsExist {
    
    return ^BOOL(NSString *tableName, FMDatabase *db) {
        
        BOOL isExist = NO;
        FMResultSet *rs = [db executeQuery:@"select count(*) as 'count' from sqlite_master where"
                                           @"type ='table' and name = ?",
                                            tableName];
        while (rs.next) {
            NSInteger count = [rs intForColumn:@"count"];
            isExist = count != 0;
        }
        [rs close];
        return isExist;
    };
}


#pragma mark - Lazy load
- (FMDatabaseQueue *)dataBaseQueue {
    if (!_databaseQueue) {
        // 数据库文件夹
        NSString *directory = YFFileManager.createDirectoryInApplicationSupport(RongCloudIMDatabase);
        // 数据库文件
        NSString *dataBaseName = [RongCloudIMDatabase stringByAppendingFormat:@"%@", [RCIMClient sharedRCIMClient].currentUserInfo.userId];
        // 创建数据库
        NSString *dataBasePath = YFFileManager.createFile(directory, dataBaseName);
        
        _databaseQueue = [FMDatabaseQueue databaseQueueWithPath:dataBasePath];
        
        if (_databaseQueue) {
            // 建表 用户信息表
            [self createUserInfoTable];
        }
    }
    return _databaseQueue;
}






@end
